﻿using AspNetId4Web.Models;
using IdentityModel;
using IdentityServer4.Models;
using IdentityServer4.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Security.Claims;
using System.Threading.Tasks;
namespace AspNetId4Web
{

    public class ProfileService : IProfileService
    {
        private readonly IServiceProvider _serviceProvider;

        public ProfileService(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            using var scope = _serviceProvider.CreateScope();
            var userMgr = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
            //按Name找不到
            //var user = await userMgr.FindByNameAsync(context.Subject.Identity.Name);
            //按Sub找得到
            string userId = context.Subject.FindFirstValue(JwtClaimTypes.Subject);
            var user = await userMgr.FindByIdAsync(userId);

            #region 非Code方式访问，context.Subject只有nation，无法获取其他claim
#if false
            var nameClaim = context.Subject.FindAll(JwtClaimTypes.Name);
            context.IssuedClaims.AddRange(nameClaim);

            var roleClaims = context.Subject.FindAll(JwtClaimTypes.Role);
            context.IssuedClaims.AddRange(roleClaims);

            var emailClaims = context.Subject.FindAll(JwtClaimTypes.Email);
            context.IssuedClaims.AddRange(emailClaims);

            var phoneNumberClaims = context.Subject.FindAll(JwtClaimTypes.PhoneNumber);
            context.IssuedClaims.AddRange(phoneNumberClaims);
#endif
            #endregion

            //手机验证码方式访问，直接获取用户的claims
            var nameClaim = new Claim(JwtClaimTypes.Name, user.UserName);
            context.IssuedClaims.Add(nameClaim);

            var roles = await userMgr.GetRolesAsync(user);
            foreach (var role in roles)
            {
                var roleClaims = new Claim(JwtClaimTypes.Role, role);
                context.IssuedClaims.Add(roleClaims);
            }

            var emailClaims = new Claim(JwtClaimTypes.Email, user.Email);
            context.IssuedClaims.Add(emailClaims);

            var phoneNumberClaims = new Claim(JwtClaimTypes.PhoneNumber, user.PhoneNumber);
            context.IssuedClaims.Add(phoneNumberClaims);

            //获取民族字段
            var nationClaim = new Claim("nation", user.Nation);
            context.IssuedClaims.Add(nationClaim);

            await Task.CompletedTask;
        }

        public async Task IsActiveAsync(IsActiveContext context)
        {
            await Task.CompletedTask;
        }
    }
}
